<template>
  <div class="page-container padding-20 query-list-container">
    <div v-show="$route.fullPath === $route.matched[1].path">
      <div class="search-container">
        <el-form :inline="true" ref="form" :model="searchData" size="small">
          <el-form-item label="关键字输入">
            <el-input v-model="searchData.idOrName" placeholder="产品ID或名称"></el-input>
          </el-form-item>
          <el-form-item label="权益类别">
            <el-select v-model="searchData.privilegeId" clearable>
              <el-option
                v-for="equity in equityList"
                :key="equity.id"
                :label="equity.name"
                :value="equity.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属品牌">
            <el-select v-model="searchData.brandId" clearable>
              <el-option
                v-for="brand in brandList"
                :key="brand.id"
                :label="brand.name"
                :value="brand.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="onSearch" size="small">查询</el-button>
          <el-button @click="onReset" size="small">重置</el-button>
        </el-form>
      </div>
      <div class="toolbar-container">
        <el-button type="primary" icon="el-icon-plus" size="small" @click="linkToAdd">新建</el-button>
        <el-button size="small" @click="linkToRedeemCode">已导出产品兑换码</el-button>
      </div>
      <el-table class="mt-20 el-table-modify" :data="tableData" border>
        <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
        <el-table-column prop="productId" align="center" label="产品ID"></el-table-column>
        <el-table-column prop="privilegeName" align="center" label="权益类别"></el-table-column>
        <el-table-column prop="brandName" align="center" label="所属品牌"></el-table-column>
        <el-table-column prop="productName" align="center" label="产品名称"></el-table-column>
        <el-table-column prop="cashAndScore" align="center" label="现金+积分价格"></el-table-column>
        <el-table-column prop="salePrice" align="center" label="现金价格"></el-table-column>
        <el-table-column prop="saleAmount" align="center" label="销量"></el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <span>{{ALL_STATUS[scope.row.status]}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="230">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="linToDetail(scope.row)">详情</el-button>
            <template v-if="scope.row.status != 'DELETED'">
              <el-button size="mini" type="text" @click="linToEdit(scope.row)">修改</el-button>
              <el-button size="mini" type="text" @click="delProduct(scope.row)">删除</el-button>
              <el-button size="mini" type="text" @click="showDialog(scope.row)">生产兑换码</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        ref="pagination"
        class="mt-20"
        background
        :page-size.sync="pageOption.pageSize"
        :total="pageOption.total"
        @size-change="onSizeChange"
        @current-change="onPageChange"
        layout="slot,->,prev,pager,next,sizes,jumper"
      >
        <span
          class="pagination-title"
        >共 {{pageOption.total}} 条记录 第 {{pageOption.page}} / {{pageOption.pageTotal}} 页</span>
      </el-pagination>
    </div>
    <router-view v-if="$route.fullPath !== $route.matched[1].path"
      :equityList="equityList" :brandList="brandList" @refresh="requestData"></router-view>
    <el-dialog title="生成兑换码" :visible.sync="visible" :close-on-click-modal="false" width="400px">
      <create-form v-if="visible" :product="selectData"  @cancel="closeDialog"/>
    </el-dialog>
  </div>
</template>

<script>
import {ALL_STATUS} from '@/utils/const';
import {equityQueryNormal} from '@/api/equityCategory';
import {enableBrands} from '@/api/brand';
import {productQuery, productDel} from '@/api/product';
import CreateForm from '../redeemCode/CreateForm';

export default {
  name: "ProductMgt",
  components: {
    CreateForm
  },
  data() {
    this.ALL_STATUS = ALL_STATUS;

    return {
      equityList: [],
      brandList: [],
      searchData: {
        idOrName: "",
        privilegeId: "",
        brandId: ""
      },
      tableData: [],
      pageOption: {
        page: 1,
        pageSize: 20,
        total: 0,
        pageTotal: 1
      },
      selectData: null,
      visible: false
    };
  },
  methods: {
    onSearch() {
      this.pageOption.page = 1;
      this.requestData();
    },
    onReset() {
      this.pageOption.page = 1;
      this.searchData.idOrName = '';
      this.searchData.privilegeId = '';
      this.searchData.brandId = '';
      this.requestData();
    },
    linkToRedeemCode() {
      this.$router.push({name: 'redeemCode'});
    },
    linkToAdd() {
      this.$router.push({name: 'addProduct'});
    },
    linToEdit(row) {
      this.$router.push({name: 'editProduct', params: {id: row.productId}});
    },
    linToDetail(row) {
      this.$router.push({name: 'productDetail', params: {id: row.productId}});
    },
    async delProduct(row) {
      try {
        this.$confirm('确定要删除该产品吗？', {
          type: 'warning',
          callback: async (action) => {
            if (action == 'confirm') {
              await productDel(row.productId)
              this.$message.success('删除成功')
              this.requestData();
            }
          }
        });
      } catch (err) {
        console.log(err)
      }
    },
    showDialog(row) {
      this.selectData = row;
      this.visible = true;
    },
    closeDialog() {
      this.visible = false;
    },
    async requestData() {
      const {page, pageSize : size} = this.pageOption
      const postData = {}, searchData = this.searchData;
      Object.keys(this.searchData).forEach(key => {
        if (this.searchData[key]) {
          postData[key] = this.searchData[key];
        }
      })
      
      const {data, total} = await productQuery({page: page - 1, size, ...postData});
      this.tableData = data;
      this.pageOption.total = total;
      this.pageOption.pageTotal = total ? Math.ceil(total / size) : 1

      if (this.$refs.pagination) {
        let childrenRefs = this.$refs.pagination.$children
        this.$nextTick(() => {
          childrenRefs.forEach(child => child.$forceUpdate())
        });
      }
    },
    async requestEquity() {
      const {data} = await equityQueryNormal();
      this.equityList = data;
    },
    async requestBrand() {
      const {data} = await enableBrands();
      this.brandList = data;
    },
    onSizeChange(size) {
      this.pageOption.pageSize = size;
      this.requestData();
    },
    onPageChange(page) {
      this.pageOption.page = page;
      this.requestData();
    }
  },
  created() {
    this.requestData();
    this.requestEquity();
    this.requestBrand();
  }
};
</script>

<style lang="scss">
.pagination-title {
  font-weight: normal;
}
</style>